﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using HikVisionTool.Helper;
using HikVisionTool.DAL;
using System.Net.Sockets;
using System.Net;
using HikVisionTool.Model;
using System.Threading;
using HikVisionTool.TcpServer;
using System.Windows.Threading;
using System.IO;
using System.Collections.ObjectModel;
using CommomDetec;

namespace 网络机高清测试
{
    /// <summary>
    /// MainWindow.xaml 的交互逻辑
    /// </summary>
    public partial class MainWindow : Window
    {

        SolidColorBrush WaitColor = new SolidColorBrush(Colors.Gold);
        SolidColorBrush PassColor = new SolidColorBrush(Colors.LightGreen);
        SolidColorBrush OkColor = new SolidColorBrush(Colors.ForestGreen);
        SolidColorBrush NgColor = new SolidColorBrush(Colors.Tomato);
        DispatcherTimer timer1 = new DispatcherTimer();
        DispatcherTimer timer2 = new DispatcherTimer();
        public string line = "";
        public string Jiwei = "";
        public int pline = 0;
        // 供应商编号，固定值
        public string lifnr = "105464";
        // 工序编号，固定值
        public string processid = "050";
        // 扫描工位，固定值
        public string wkposition = "";
        public string order = "";
        public string code = "";


        DateTime scanTime = DateTime.Now;
        BLL.HikDataBLL hikDataBLL;
        BLL.MesBLL mesBLL = new BLL.MesBLL();

        object listLock = new object();
        object upLock = new object();
        List<Sql5Helper.t_Item> t_Items = new List<Sql5Helper.t_Item>();
        ViewModel.MainViewModel viewModel = new ViewModel.MainViewModel();
        public Sql3Helper.t_DD_UserDetail userModel = null;


        //高清测试
        string operation = "高清测试";

        public MainWindow()
        {
            HandyControl.Tools.ConfigHelper.Instance.SetLang("zh-cn");
            InitializeComponent();
            this.WindowStartupLocation = WindowStartupLocation.Manual;
            this.Left = 0;
            this.Top = 0;
            this.Title = operation + "过站与数采";
        }
        private void InitLines()
        {
            ComboBoxWkPosition.Items.Add(operation);
            if (operation == "高清测试")
            {
                t_Items = mesBLL.GetIPCLines().OrderBy(it => it.itemName.Length).ThenBy(it => it.itemName).ToList();
                foreach (var item in t_Items)
                {
                    ComboBoxLine.Items.Add(item.itemName);
                }
            }
        }
        private void Window_Loaded(object sender, RoutedEventArgs e)
        {
            try
            {
                InitLines();

                Dictionary<string, string> dic = ConfigHelper.ReadAll();
                //TextBoxName.Text = dic["name"];
                ComboBoxLine.SelectedValue = dic["line"];
                ComboBoxWkPosition.SelectedValue = dic["wkposition"];
                TextBoxJiWei.Text = dic["jiwei"];
                viewModel.Enable = true;
                viewModel.Items = new ObservableCollection<ViewModel.MainViewModel.Item>();
                timer1.Tick += new EventHandler(timer1_Tick);
                timer1.Interval = new TimeSpan(20000000);
                timer2.Tick += new EventHandler(timer2_Tick);
                timer2.Interval = new TimeSpan(100000000);
                hikDataBLL = new BLL.HikDataBLL(this);
                this.DataContext = viewModel;
            }
            catch (Exception ex)
            {
                if (ex.Message.Contains("SQL"))
                {
                    HandyControl.Controls.MessageBox.Error("数据库连接异常");
                }
                else
                {
                    HandyControl.Controls.MessageBox.Error(ex.Message);
                }
                FileHelper.WriteLog(ex.ToString());
            }
        }
        bool change = false;
        private void timer1_Tick(object sender, EventArgs e)
        {
            try
            {
                FindFile();
                Dispatcher.Invoke(() =>
                {
                    if (viewModel.Items.Count > 0 && change)
                    {
                        SetPie();
                        List.ScrollIntoView(List.Items[List.Items.Count - 1]);
                        TextBoxOrder.Text = order;
                        change = false;
                    }
                });
            }
            catch (Exception ex)
            {
                HandyControl.Controls.MessageBox.Error(ex.Message);
                FileHelper.WriteLog(ex.ToString());
            }
        }
        private void timer2_Tick(object sender, EventArgs e)
        {
            try
            {
                lock (upLock)
                {
                    Task.Factory.StartNew(() =>
                    {
                        try
                        {
                            if (mesBLL.Sql3Check() == false)
                            {
                                return;
                            }
                            hikDataBLL.UpOfflineData();
                        }
                        catch (Exception ex)
                        {
                            FileHelper.WriteLog(ex.ToString());
                        }
                    });
                }
            }
            catch (Exception ex)
            {
                HandyControl.Controls.MessageBox.Error(ex.Message);
                FileHelper.WriteLog(ex.ToString());
            }
        }
        private void FindFile()
        {
            try
            {
                string path = @"d:\HIK\" + DateTime.Today.ToString("yyyyMM") + "\\" + DateTime.Today.ToString("yyyyMMdd");
                //记录前一次最新文件生成时间
                if (!Directory.Exists(path))
                {
                    return;
                }
                DirectoryInfo directory = new DirectoryInfo(path);
                if (directory.GetFiles().Length == 0)
                {
                    return;
                }
                FileInfo fi = directory.GetFiles().OrderByDescending(it => it.CreationTime).First();
                //找到新生成的 txt文件
                if (fi.CreationTime > scanTime)
                {
                    //dosomething:  可以根据detectionResult，调接口将检测结果存后台
                    string pk = "";
                    ViewModel.MainViewModel.Item item1 = null;
                    lock (listLock)
                    {
                        item1 = viewModel.Items.Where(it => it.BarCode == code).First();
                        DateTime time = DateTime.Now;
                        pk = $"{lifnr}{code}{time.ToString("yyyyMMddHHMMssfff")}";
                        if (item1 != null)
                        {
                            MesTool.Model.HttpModel.CheckdataDto checkdataPost = new MesTool.Model.HttpModel.CheckdataDto()
                            {
                                serial_number = code,
                                operation_name = operation,
                                user_name = userModel.username,
                                quality ="OK",
                            };
                            string errMsg = "";
                            bool isPass = mesBLL.PostCheckdata(checkdataPost, ref errMsg);
                            if (isPass == false)
                            {
                                item1.BackColor = NgColor;
                                errMsg = "过站记录保存失败，请重新测试\r\n" + errMsg;
                                HandyControl.Controls.MessageBox.Error(errMsg);
                                return;
                            }
                            MesTool.Model.HttpModel.BarcodestatusDto barcodestatusPost = new MesTool.Model.HttpModel.BarcodestatusDto
                            {
                                serial_number = code,
                                operation_name = operation,
                                quality = "OK",
                            };
                            isPass = mesBLL.PostBarcodestatus(barcodestatusPost, ref errMsg);
                            if (isPass == false)
                            {
                                item1.BackColor = NgColor;
                                errMsg = "更新序列号状态失败，请重新测试\r\n" + errMsg;
                                HandyControl.Controls.MessageBox.Error(errMsg);
                                return;
                            }
                            item1.BackColor = PassColor;

                        }
                    }
                    Task.Factory.StartNew(() =>
                    {
                        StringBuilder sb = new StringBuilder();
                        using (FileStream fileStream = new FileStream(fi.FullName, FileMode.Open))
                        {
                            StreamReader sr = new StreamReader(fileStream, Encoding.Default);
                            string line;
                            while ((line = sr.ReadLine()) != null)
                            {
                                sb.AppendLine(line);
                            }
                            sr.Close();
                            fileStream.Close();
                        }
                        string[] temp_data = sb.ToString().Split(Environment.NewLine.ToArray(), StringSplitOptions.RemoveEmptyEntries);
                        var detectionResult = new DetectionResult();
                        detectionResult.Serial = code;
                        detectionResult.Result = ResultStatus.SUCCESS;
                        detectionResult.StartTime = scanTime.ToString("G");
                        detectionResult.EndTime = fi.CreationTime.ToString("G");
                        int index = 0;
                        foreach (var item_array in temp_data)
                        {
                            string[] result_data = item_array.Split((char)0x09);
                            int input = 0;
                            if (int.TryParse(result_data.FirstOrDefault(), out input))
                            {
                                CheckSubItem f = new CheckSubItem
                                {
                                    ID = (index + 1).ToString(),
                                    Name = result_data.Skip(2).Take(1).FirstOrDefault(),
                                    Description = result_data.Skip(5).Take(1).FirstOrDefault(),
                                    StartTime = scanTime.ToString("G"),
                                    EndTime = fi.CreationTime.ToString("G"),
                                    Result = ResultStatus.SUCCESS,
                                };
                                var s = new CommomDetec.Item()
                                {
                                    ID = (index + 1).ToString(),
                                    Type = "KeyInfo",
                                    Name = result_data.Skip(2).Take(1).FirstOrDefault(),
                                    Description = result_data.Skip(5).Take(1).FirstOrDefault(),
                                    Result = ResultStatus.SUCCESS,
                                };
                                f.Items.Add(s);
                                detectionResult.CheckSubItems.Add(f);
                                index++;
                            }
                        }
                        hikDataBLL.PostHikDate(detectionResult, item1.MoCode, pk);
                        item1.Pk_id = pk;
                        change = true;
                    });
                }
            }
            catch (Exception ex)
            {
                HandyControl.Controls.MessageBox.Error(ex.Message);
                FileHelper.WriteLog(ex.ToString());
            }
        }
        private void BorderStart_PreviewMouseUp(object sender, MouseButtonEventArgs e)
        {
            try
            {
                if (PackIconStart.Kind == MaterialDesignThemes.Wpf.PackIconKind.Play)
                {
                    if (ComboBoxLine.Text == "")
                    {
                        HandyControl.Controls.MessageBox.Warning("请先选择线别!");
                        return;
                    }
                    if (ComboBoxWkPosition.Text == "")
                    {
                        HandyControl.Controls.MessageBox.Warning("请先选择工位!");
                        return;
                    }
                    if (TextBoxJiWei.Text == "")
                    {
                        HandyControl.Controls.MessageBox.Warning("请先输入机位!");
                        return;
                    }
                    if (int.TryParse(TextBoxJiWei.Text, out int a) == false)
                    {
                        HandyControl.Controls.MessageBox.Warning("机位输入错误!");
                        return;
                    }
                    if (TextBoxName.Text.Trim() == "")
                    {
                        HandyControl.Controls.MessageBox.Warning("请先输入工号!");
                        return;
                    }
                    userModel = mesBLL.GetUser(TextBoxName.Text.Trim());
                    if (userModel == null)
                    {
                        HandyControl.Controls.MessageBox.Error("姓名获取失败");
                        return;
                    }

                    line = ComboBoxLine.Text;
                    TextBoxName.Text = userModel.username;
                    wkposition = ComboBoxWkPosition.Text;
                    Jiwei = TextBoxJiWei.Text;
                    viewModel.Enable = false;
                    BorderStart.Background = NgColor;
                    PackIconStart.Kind = MaterialDesignThemes.Wpf.PackIconKind.Stop;
                    PoptipStart.Content = "停止采集";
                    timer1.Start();
                    timer2.Start();
                }
                else
                {
                    if (userModel != null)
                    {
                        TextBoxName.Text = userModel.jobnumber;
                    }
                    viewModel.Enable = true;
                    BorderStart.Background = OkColor;
                    PackIconStart.Kind = MaterialDesignThemes.Wpf.PackIconKind.Play;
                    PoptipStart.Content = "开始采集";
                    timer1.Stop();
                }
            }
            catch (Exception ex)
            {
                if (ex.Message.Contains("SQL"))
                {
                    HandyControl.Controls.MessageBox.Error("数据库连接异常");
                }
                else
                {
                    HandyControl.Controls.MessageBox.Error(ex.Message);
                }
                FileHelper.WriteLog(ex.ToString());
            }
        }

        private void BorderStart_MouseMove(object sender, MouseEventArgs e)
        {
            this.Cursor = Cursors.Hand;
        }

        private void BorderStart_MouseLeave(object sender, MouseEventArgs e)
        {
            this.Cursor = Cursors.Arrow;
        }

        private void Window_Closing(object sender, System.ComponentModel.CancelEventArgs e)
        {
            bool wait = false;
            lock (listLock)
            {
                foreach (var item in viewModel.Items)
                {
                    if (item.BackColor != WaitColor && item.Pk_id == null)
                    {
                        wait = true;
                        break;
                    }
                }
            }
            if (wait == true)
            {
                MessageBoxResult messageBoxResult = HandyControl.Controls.MessageBox.Ask("还有未上传的数据，是否退出？");
                if (messageBoxResult != MessageBoxResult.OK)
                {
                    e.Cancel = true;
                }
            }
        }

        private void Window_Closed(object sender, EventArgs e)
        {
            ConfigHelper.Write("wkposition", ComboBoxWkPosition.Text);
            ConfigHelper.Write("line", ComboBoxLine.Text);
            ConfigHelper.Write("jiwei", TextBoxJiWei.Text);
            if (userModel != null)
            {
                ConfigHelper.Write("name", userModel.jobnumber);
            }
            System.Environment.Exit(0);
        }

        private void Button_Click(object sender, RoutedEventArgs e)
        {
            order = "";
            TextBoxOrder.Text = order;
        }

        public void SetPie()
        {
            int pass = 0;
            int fail = 0;
            lock (listLock)
            {
                foreach (var item in viewModel.Items)
                {
                    if (item.BackColor == NgColor)
                    {
                        fail++;
                    }
                    if (item.BackColor == PassColor || item.BackColor == OkColor)
                    {
                        pass++;
                    }
                }
            }
            if (viewModel.Pass[0] != pass || viewModel.Fail[0] != fail)
            {
                viewModel.Pass[0] = pass;
                viewModel.Fail[0] = fail;
            }
        }
        public void SetList(string serial, string wknum)
        {
            Dispatcher.Invoke(() =>
            {
                lock (listLock)
                {
                    ViewModel.MainViewModel.Item item = new ViewModel.MainViewModel.Item()
                    {
                        No = viewModel.Items.Count + 1,
                        MoCode = wknum,
                        BarCode = serial,
                        BackColor = WaitColor,
                        Pk_id = null
                    };
                    if (viewModel.Items.Count > 0)
                    {
                        var model = viewModel.Items.Where(it => it.BarCode == serial).First();
                        if (model == null)
                        {
                            viewModel.Items.Add(item);
                            List.ScrollIntoView(List.Items[item.No]);
                        }
                        else
                        {
                            model.Pk_id = null;
                            model.BackColor = WaitColor;
                            List.ScrollIntoView(List.Items[model.No]);
                        }
                    }
                    else
                    {
                        viewModel.Items.Add(item);
                        List.ScrollIntoView(List.Items[item.No]);
                    }
                }
            });
        }
        void BarCode_BarCodeEvent(BLL.BardCodeHooK.BarCodes barCode)
        {
            //海康扫码为"\0C05551450"，把"\0"屏蔽掉
            string serial = barCode.BarCode.Replace("\r", "").Replace("\0", "").ToUpper();
            //dosomething: 做序列号校验（工序），无校验则直接响应成功
            string wknum = "";
            string errMsg = "";
            bool isPass = mesBLL.OperationCheck(serial, operation, ref errMsg, ref wknum);
            if (isPass == false)
            {
                HandyControl.Controls.MessageBox.Error(errMsg);
                return;
            }
            isPass = mesBLL.CheckWknum(ref order, wknum, ref errMsg);
            if (isPass == false)
            {
                HandyControl.Controls.MessageBox.Error(errMsg);
                return;
            }
            SetList(serial, wknum);
            code = serial;
            scanTime = DateTime.Now;
        }
    }
}
